import { ref, computed, onMounted } from 'vue'
import { defineStore } from 'pinia'

import {
  getGoodsApi,
  addGoodsApi,
  deleteGoodsApi,
  editGoodsApi,
  getGoodsByIdApi,
} from '@/api/goods'

export const useCounterStore = defineStore('counter', () => {
  //=====数据=====
  const goods = ref([])
  const isClick = ref(1)

  //=====计算属性=====

  //=====方法=====
  const fn = async () => {
    const res = await getGoodsApi()
    goods.value = res
  }

  //添加
  const addGoods = async (name, price) => {
    await addGoodsApi(name, price)
    fn()
  }

  //删除
  const deleteGoods = async (id) => {
    await deleteGoodsApi(id)
    fn()
  }

  //回显数据
  const getGoodsById = (id) => {
    const res = getGoodsByIdApi(id)
    return res
  }

  //修改
  const editGoods = async (id, name, price) => {
    await editGoodsApi(id, name, price)
    fn()
  }

  //=====周期函数=====
  onMounted(() => {
    fn()
  })

  return { goods, isClick, addGoods, deleteGoods, editGoods, getGoodsById }
})
